<template>
  <div>
    <div class="cm">
      <p>发表评论</p>
      <hr>
      <textarea placeholder="请输入要BB的内容（做多吐槽120字）" maxlength="120" v-model="msg"></textarea>
      <input type="button" value="发表评论" @click="commit">
      <div class="cm-content" v-for="(item, index) in comments" :key="index">
        <div>
          <span>第{{index + 1}}楼</span>
          <span>用户：{{item.user_name}}</span>
          <span>发表时间：{{item.add_time | dateFormat}}</span>
        </div>
        <p>{{item.content}}</p>
      </div>
      <input type="button" value="加载更多" class="more" @click="getMore">
    </div>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      comments: [],
      pageIndex: 1,
      msg: ""
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      this.$http
        .get(
          "api/getcomments/" + this.cmid + "?pageindex=" + this.pageIndex + ""
        )
        .then(result => {
          if (result.body.status == 0) {
            // this.comments = result.body.message
            this.comments = this.comments.concat(result.body.message);
          }
        });
    },
    getMore() {
      this.pageIndex++;
      this.getComments();
    },
    // 提交评论功能的实现
    commit(){
        // 校验数据
        if (this.msg.trim().length == 0) {
            return Toast('评论内容不能为空')
        }
        // 提交评论数据
        this.$http.post("api/postcomment/"+this.cmid+"",{content: this.msg.trim()}).then(result => {
            if (result.body.status == 0) {
                
                var cmt = {
                    user_name: '匿名用户',
                    add_time:Date.now(),
                    content:this.msg.trim()
                }
                this.comments.unshift(cmt) // 发表评论后直接显示
                this.msg = ''
                Toast('评论成功')
            }else{
                Toast('评论失败，请重试！')
            }
        })
    }
  },
  props: ["cmid"]
};
</script>
<style lang="less" scoped>
.cm {
  width: 100%;
  textarea {
    width: 100%;
    height: 80px;
    border: 1px solid #cccccc;
    outline: none;
  }
  input {
    width: 100%;
    height: 30px;
    background-color: rgb(9, 76, 201);
    color: #fff;
    text-align: center;
    line-height: 30px;
    outline: none;
  }
  .cm-content {
    width: 100%;
    div {
      width: 100%;
      height: 20px;
      background-color: #ccc;
      overflow: hidden;
    }
    p {
      width: 100%;
      min-height: 30px;
      border: 1px solid #eee;
    }
  }
  .more {
    width: 100%;
    height: 40px;
    background-color: rgb(219, 28, 194);
    color: #fff;
  }
}
</style>
